package middleware

import (
	"github.com/gin-gonic/gin"
	"meituan/utils/auth"
	"meituan/utils/config"
	"regexp"
)

func AuthControl(context *gin.Context) {
	uri := context.Request.RequestURI
	loadConfig, _ := config.LoadConfig()
	for _, tour := range loadConfig.Gin.TouristUrl {

		res, _ := regexp.Match(tour, []byte(uri))
		// 假如匹配到不需要登陆的url 退出函数 不检查用户
		if res {
			context.Next()
			return
		}
	}

	realm := auth.DefaultRealm{}
	subject, error := auth.FromContext(realm, context)
	if error != nil {
		context.JSON(403, gin.H{
			"code": 403,
			"msg":  "用户未登录",
		})
		context.Abort()
	} else {
		context.Set("user", subject)
		context.Next()
	}
}
